package com.foreveross.chameleon.manager.task;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Set;
import java.util.zip.ZipException;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.darin.cl.http.CLHttpProgressImpl;
import com.darin.cl.http.CLHttpUtil;
import com.darin.cl.http.CLHttpUtil.RequestMethod;
import com.darin.cl.task.CLTask;
import com.darin.cl.util.CLFileUtil;
import com.foreveross.URL;
import com.foreveross.chameleon.manager.AutoDownloadHelper;
import com.foreveross.chameleon.manager.BroadCastManager;
import com.foreveross.chameleon.manager.CubeContentManager;
import com.foreveross.chameleon.manager.CubeContentStatus;
import com.foreveross.pojo.CubeModule;
import com.foreveross.pojo.CubeModuleDownloadInfo;

public class InstallModuleTask  extends CLTask<Object, Object, String>{
	
	private CubeModuleDownloadInfo mBean = null;
	private CLHttpUtil mClHttpUtil;
	private Context mContext;
	
	public InstallModuleTask(CubeModuleDownloadInfo bean,
			CLHttpUtil clHttpUtil , Context context) {
		super();
		this.mBean = bean;
		this.mContext = context;
	}
	
	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		super.onPreExecute();
		mBean.getModule().setModuleType(CubeModule.INSTALLING);
		BroadCastManager.updateProgress(mContext, mBean.getModule(), -1);
		BroadCastManager.sentModuleDownloadCount(mContext);
	}

	@Override
	public String doInBackground(Object... params) throws Exception {
		mClHttpUtil = new CLHttpUtil(mBean.getDownloadUrl());
		mClHttpUtil.downloadFile(mBean.getFilePath(), RequestMethod.GET, null, new CLHttpProgressImpl() {
			
			
			@Override
			public void onProcessChange(long process, long max, Object flag) {
				MathContext mc = new MathContext(3, RoundingMode.HALF_DOWN);
				BigDecimal db1 = new BigDecimal(process);
				BigDecimal db2 = new BigDecimal(max);
				BigDecimal result = (db1.divide(db2, mc).multiply(new BigDecimal(100), mc));
				if (process < max){
					mBean.getModule().setProgress(result.intValue());
					BroadCastManager.updateProgress(mContext, mBean.getModule(), result.intValue());
				} else {
					mBean.setDownSuccess(true);
				}
				
			}
			
			@Override
			public void onProcessEnd() {
				// 下载完成后进行解压操作
				boolean unZip = false;
				try {
					CLFileUtil.unZipFile(mBean.getFilePath(), mBean.getFileDir());
					unZip = true;
				} catch (ZipException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				// 解压成功后改变模块状态
				CubeModule module = mBean.getModule();
				CubeContentStatus contentStatus = CubeContentManager.getInstance().getmCubeContentStatus();
				if (unZip){
					contentStatus.add2Main(module);
					if(module.isHidden()) {
						contentStatus.removeFormMain(module);
					}	
					module.setModuleType(CubeModule.INSTALLED);
					if(isExist(mContext , module,"icon.img")) {
						module.setIcon(URL.getSdPath(mContext, module.getIdentifier()+"/icon.img"));
					}else if(isExist(mContext ,module,"icon.png")) {
						module.setIcon(URL.getSdPath(mContext, module.getIdentifier()+"/icon.png"));
					}
					contentStatus.removeFormUninstalled(module);
					contentStatus.add2Installed(module);
					CubeContentManager contentManager = CubeContentManager.getInstance();
					Set<CubeModule> storedSet = contentManager.getCubeContent().getModules();
					storedSet.add(module);
					BroadCastManager.updateProgress(mContext, module, 101);
					BroadCastManager.refreshModule(mContext, "install" , module);
					CubeContentManager.getInstance().save(mContext ,contentManager.getCubeContent());
					Log.v("Depends", "安装成功，开始检查依赖");
					AutoDownloadHelper.getInstance().finishDownload(module , true);
					BroadCastManager.sentModuleDownloadCount(mContext);
					if(AutoDownloadHelper.getInstance().getProgressCount()==0) {
						BroadCastManager.sentModuleDownloadFinsh(mContext);
						AutoDownloadHelper.getInstance().clear();
					}
					BroadCastManager.refreshMainPage(mContext, module);
					ArrayList<CubeModule> result = CubeContentManager.getInstance().checkDepends(module.getIdentifier());
					for (CubeModule m : result) {
						if (m.getPrivileges() != null) {
							CubeContentManager.getInstance().downLoadOrUpgradeModule(m , mContext);
						}
					}
				} else {
					if(module !=null) {
						module.setModuleType(CubeModule.UNINSTALL);
						contentStatus.removeFormMain(module);
						AutoDownloadHelper.getInstance().finishDownload(module , false);
						BroadCastManager.sentModuleDownloadCount(mContext);
						if(AutoDownloadHelper.getInstance().getProgressCount()==0) {
							BroadCastManager.sentModuleDownloadFinsh(mContext);
							AutoDownloadHelper.getInstance().clear();
						}
						Toast.makeText(mContext, "网络状态不稳定!", Toast.LENGTH_SHORT).show();
						BroadCastManager.refreshMainPage(mContext, module);
						BroadCastManager.updateProgress(mContext, module, 101);
					}
				}
			}
		});
		
		
		return null;
	}
	
	@Override
	public void doOnSuccess(String result) {
		
	}
	
	@Override
	protected void doOnException(Exception exception) {
		// TODO Auto-generated method stub
		super.doOnException(exception);
	}
	
	@Override
	protected void onFinish() {
		// TODO Auto-generated method stub
		super.onFinish();
		mClHttpUtil.shutdown();
	}
	
	public boolean isExist(Context context , CubeModule cubeModule,String name) {
		String path = URL.getSdPath(context, cubeModule.getIdentifier())+"/"+name;
		File f= new File(path);
		if (f.exists()) {
			return true;
		} else {
			return false;
		}
	}

}
